// API Mock定义文件
// 使用vite-plugin-mock格式定义所有模拟接口

// 生成随机ID
const generateId = () => Math.random().toString(36).substr(2, 9)

// 生成随机日期
const generateDate = () => {
  const start = new Date(2023, 0, 1)
  const end = new Date()
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).toISOString().split('T')[0]
}

// 模拟数据生成函数
const mockApi = [
  // ============== 用户认证相关 API ==============
  {
    url: '/api/auth/login',
    method: 'post',
    response: ({ body }) => {
      const { email, password } = body
      
      // 模拟登录验证
      if (email && password) {
        return {
          success: true,
          data: {
            token: 'mock-token-' + Date.now(),
            userInfo: {
              id: 'user-' + generateId(),
              name: '系统管理员',
              email: email,
              avatar: 'https://picsum.photos/id/1005/200/200',
              role: 'admin',
              createdAt: generateDate()
            }
          },
          message: '登录成功'
        }
      }
      
      return {
        success: false,
        message: '用户名或密码错误',
        code: 401
      }
    }
  },
  
  {
    url: '/api/auth/logout',
    method: 'post',
    response: () => {
      return {
        success: true,
        message: '登出成功'
      }
    }
  },
  
  // ============== 用户管理相关 API ==============
  {
    url: '/api/users/current',
    method: 'get',
    response: () => {
      return {
        success: true,
        data: {
          id: 'user-current',
          name: '系统管理员',
          email: 'admin@example.com',
          avatar: 'https://picsum.photos/id/1005/200/200',
          role: 'admin',
          permissions: ['*'],
          createdAt: generateDate()
        }
      }
    }
  },
  
  {
    url: '/api/users',
    method: 'get',
    response: ({ query }) => {
      const page = parseInt(query.page) || 1
      const pageSize = parseInt(query.pageSize) || 10
      const keyword = query.keyword || ''
      
      // 模拟用户数据
      const mockUsers = []
      for (let i = 0; i < 20; i++) {
        mockUsers.push({
          id: 'user-' + i,
          name: `用户${i + 1}`,
          email: `user${i + 1}@example.com`,
          avatar: `https://picsum.photos/id/${1010 + i}/200/200`,
          role: i % 3 === 0 ? 'admin' : i % 3 === 1 ? 'editor' : 'viewer',
          status: i % 5 === 0 ? 'inactive' : 'active',
          createdAt: generateDate()
        })
      }
      
      // 过滤和分页
      const filteredUsers = keyword
        ? mockUsers.filter(user => 
            user.name.includes(keyword) || 
            user.email.includes(keyword)
          )
        : mockUsers
      
      const startIndex = (page - 1) * pageSize
      const endIndex = startIndex + pageSize
      const paginatedUsers = filteredUsers.slice(startIndex, endIndex)
      
      return {
        success: true,
        data: {
          list: paginatedUsers,
          total: filteredUsers.length,
          page,
          pageSize
        }
      }
    }
  },
  
  {
    url: '/api/users/create',
    method: 'post',
    response: ({ body }) => {
      return {
        success: true,
        message: '用户创建成功',
        data: {
          ...body,
          id: 'user-' + generateId(),
          createdAt: new Date().toISOString().split('T')[0],
          status: 'active'
        }
      }
    }
  },
  
  {
    url: '/api/users/update',
    method: 'put',
    response: ({ body }) => {
      return {
        success: true,
        message: '用户更新成功',
        data: body
      }
    }
  },
  
  {
    url: '/api/users/delete',
    method: 'delete',
    response: ({ query }) => {
      const { id } = query
      return {
        success: true,
        message: '用户删除成功',
        data: { id }
      }
    }
  },
  
  // ============== 角色管理相关 API ==============
  {
    url: '/api/roles',
    method: 'get',
    response: () => {
      const roles = [
        {
          id: 'role-admin',
          name: '超级管理员',
          description: '拥有系统所有权限',
          permissions: ['*'],
          createdAt: generateDate()
        },
        {
          id: 'role-editor',
          name: '编辑',
          description: '可以编辑内容，但不能管理用户',
          permissions: ['content:read', 'content:write', 'media:upload'],
          createdAt: generateDate()
        },
        {
          id: 'role-viewer',
          name: '查看者',
          description: '只能查看内容，不能编辑',
          permissions: ['content:read'],
          createdAt: generateDate()
        }
      ]
      
      return {
        success: true,
        data: roles
      }
    }
  },
  
  {
    url: '/api/permissions',
    method: 'get',
    response: () => {
      const permissions = [
        { id: 'content:read', name: '内容查看', description: '查看系统内容' },
        { id: 'content:write', name: '内容编辑', description: '编辑系统内容' },
        { id: 'user:manage', name: '用户管理', description: '管理系统用户' },
        { id: 'role:manage', name: '角色管理', description: '管理系统角色' },
        { id: 'media:upload', name: '媒体上传', description: '上传媒体文件' },
        { id: 'system:config', name: '系统配置', description: '配置系统参数' }
      ]
      
      return {
        success: true,
        data: permissions
      }
    }
  },
  
  // ============== SEO 相关 API ==============
  {
    url: '/api/seo/analyze',
    method: 'post',
    response: ({ body }) => {
      const { url, content } = body
      
      return {
        success: true,
        data: {
          score: Math.floor(Math.random() * 30) + 70, // 70-100分
          issues: [
            {
              type: 'warning',
              message: '页面标题过长',
              severity: 2
            },
            {
              type: 'info',
              message: '建议增加元描述',
              severity: 1
            }
          ],
          recommendations: [
            '优化页面标题长度至60字符以内',
            '添加元描述以提高点击率'
          ],
          url,
          analyzedAt: new Date().toISOString()
        }
      }
    }
  },
  
  {
    url: '/api/seo/settings',
    method: 'get',
    response: () => {
      return {
        success: true,
        data: {
          siteName: '管理系统',
          defaultTitle: '管理系统 - 后台管理平台',
          defaultMetaDescription: '这是一个现代化的管理系统后台',
          keywords: '管理系统,后台,admin',
          robots: 'index, follow',
          googleAnalyticsId: 'UA-XXXXXX-X',
          baiduAnalyticsId: 'XXXXXXXXXX'
        }
      }
    }
  },
  
  {
    url: '/api/seo/settings',
    method: 'post',
    response: ({ body }) => {
      return {
        success: true,
        message: 'SEO设置保存成功',
        data: body
      }
    }
  },
  
  // 基础SEO设置API - 与src/api/seo.js中的getSeoSettings和saveSeoSettings函数对应
  {
    url: '/api/seo/basic-settings',
    method: 'get',
    response: () => {
      return {
        success: true,
        data: {
          siteName: '管理系统',
          defaultTitle: '管理系统 - 后台管理平台',
          defaultMetaDescription: '这是一个现代化的管理系统后台',
          keywords: '管理系统,后台,admin',
          robots: 'index, follow',
          googleAnalyticsId: 'UA-XXXXXX-X',
          baiduAnalyticsId: 'XXXXXXXXXX'
        }
      }
    }
  },
  
  {
    url: '/api/seo/basic-settings',
    method: 'post',
    response: ({ body }) => {
      return {
        success: true,
        message: '基础SEO设置保存成功',
        data: body
      }
    }
  },
  
  {
    url: '/api/seo/health',
    method: 'get',
    response: () => {
      return {
        success: true,
        data: {
          status: 'good',
          score: 85,
          lastChecked: generateDate(),
          issues: 2,
          sitemapStatus: 'generated',
          robotsStatus: 'configured'
        }
      }
    }
  },
  
  // ============== 案例管理相关 API ==============
  {
    url: '/api/case/list',
    method: 'get',
    response: ({ query }) => {
      const page = parseInt(query.page) || 1
      const pageSize = parseInt(query.pageSize) || 10
      
      // 模拟案例数据
      const mockCases = []
      for (let i = 0; i < 50; i++) {
        mockCases.push({
          id: 'case-' + i,
          title: `案例标题${i + 1}`,
          client: `客户名称${i + 1}`,
          category: i % 4 === 0 ? '网站建设' : i % 4 === 1 ? 'SEO优化' : i % 4 === 2 ? '内容营销' : '社交媒体',
          status: i % 3 === 0 ? 'completed' : i % 3 === 1 ? 'ongoing' : 'planned',
          startDate: generateDate(),
          endDate: i % 3 === 0 ? generateDate() : null,
          description: `这是案例${i + 1}的详细描述，包含项目背景、目标、实施过程和成果。`,
          coverImage: `https://picsum.photos/id/${2000 + i}/600/400`,
          createdAt: generateDate()
        })
      }
      
      // 分页
      const startIndex = (page - 1) * pageSize
      const endIndex = startIndex + pageSize
      const paginatedCases = mockCases.slice(startIndex, endIndex)
      
      return {
        success: true,
        data: {
          list: paginatedCases,
          total: mockCases.length,
          page,
          pageSize
        }
      }
    }
  },
  
  {
    url: '/api/case/detail/(.*)',
    method: 'get',
    response: ({ params }) => {
      const { 0: id } = params
      
      return {
        success: true,
        data: {
          id,
          title: `案例详情标题 - ${id}`,
          client: '详细客户名称',
          category: '网站建设',
          status: 'completed',
          startDate: generateDate(),
          endDate: generateDate(),
          description: '这是一个详细的案例描述，包含项目的各个方面。\n项目背景：客户需要一个现代化的企业网站。\n项目目标：提升品牌形象，增加线上转化率。\n实施过程：经过需求分析、设计、开发、测试等阶段。\n项目成果：网站访问量提升50%，转化率提升30%。',
          coverImage: `https://picsum.photos/id/${2050}/800/500`,
          gallery: [
            `https://picsum.photos/id/${2051}/800/500`,
            `https://picsum.photos/id/${2052}/800/500`,
            `https://picsum.photos/id/${2053}/800/500`
          ],
          results: {
            trafficIncrease: '50%',
            conversionRate: '30%',
            roi: '200%'
          },
          createdAt: generateDate(),
          updatedAt: generateDate()
        }
      }
    }
  },
  
  {
    url: '/api/case/add',
    method: 'post',
    response: ({ body }) => {
      return {
        success: true,
        message: '案例添加成功',
        data: {
          ...body,
          id: 'case-' + generateId(),
          createdAt: new Date().toISOString().split('T')[0]
        }
      }
    }
  },
  
  {
    url: '/api/case/update/(.*)',
    method: 'put',
    response: ({ body, params }) => {
      const { 0: id } = params
      
      return {
        success: true,
        message: '案例更新成功',
        data: {
          ...body,
          id,
          updatedAt: new Date().toISOString().split('T')[0]
        }
      }
    }
  },
  
  {
    url: '/api/case/delete/(.*)',
    method: 'delete',
    response: ({ params }) => {
      const { 0: id } = params
      
      return {
        success: true,
        message: '案例删除成功',
        data: { id }
      }
    }
  },
  
  // ============== 系统相关 API ==============
  {
    url: '/api/system/check-updates',
    method: 'get',
    response: () => {
      return {
        success: true,
        data: {
          currentVersion: '1.0.0',
          latestVersion: '1.0.1',
          updateAvailable: true,
          releaseNotes: '修复了一些bug，优化了系统性能',
          downloadUrl: '#',
          lastChecked: new Date().toISOString()
        }
      }
    }
  }
]

export default mockApi